<template>
  <div id="questionsView">
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="title" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.title" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item field="tags" label="标签" style="min-width: 240px">
        <a-input-tag v-model="searchParams.tags" placeholder="请输入标签" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">查找</a-button>
      </a-form-item>
    </a-form>
    <a-divider :size="1" />
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      @sorter-change="handleSorterChange"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        showJumper: true,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag
            v-for="(tag, index) of record.tags"
            :key="index"
            color="arcoblue"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="toQuestionPage(record)">
            查看
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref, watchEffect } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
  QuestionVO,
  UserControllerService,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { TableColumnData } from "@arco-design/web-vue";
import store from "@/store";
import { ACCESS_ENUM } from "@/access/accessEnum";
import { IconCheck } from "@arco-design/web-vue/es/icon";

const tableRef = ref();

const dataList = ref<Array<QuestionVO>>([]);
const questionIdList = ref<Array<number>>([]);
const total = ref(0);
const searchParams = ref<QuestionQueryRequest>({
  id: undefined,
  userId: undefined,
  title: "",
  tags: [],
  pageSize: 10,
  current: 1,
  sortField: "id",
  sortOrder: "ascend",
});

const loadData = async () => {
  const res = await QuestionControllerService.pageQueryQuestionVo(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data?.records ?? [];
    total.value = res.data?.total ?? 0;
  } else {
    message.error("加载失败，" + res.message);
  }
  let loginUser = store.state.user.loginUser;
  if (loginUser && loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN) {
    // 获取用户通过题目id
    const res = await UserControllerService.getMyAcceptedQuestion();
    if (res.code === 0) {
      questionIdList.value = res.data ?? [];
    } else {
      message.error("加载失败，" + res.message);
    }
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const columns = ref<TableColumnData[]>([
  {
    title: "题目名称",
    dataIndex: "title",
    render: ({ record }) => {
      const completedSet = computed(() => new Set(questionIdList.value));
      const isCompleted = completedSet.value.has(record.id);
      return h("div", { class: "title-wrapper" }, [
        // 图标前置部分
        isCompleted &&
          h(IconCheck, {
            style: "color: #00b42a; margin-right: 8px", // 调整间距方向
          }),
        // 题目名称
        h("span", record.title),
      ]);
    },
  },
  {
    title: "标签",
    slotName: "tags",
  },
  {
    title: "分值",
    dataIndex: "score",
  },
  {
    title: "通过率",
    dataIndex: "ratio",
    // 关键修改点：自定义渲染时间消耗列
    render: ({ record }) => `${record.ratio ?? "--"}%`,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    slotName: "optional",
  },
]);

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const router = useRouter();

// 处理排序逻辑
const handleSorterChange = (
  dataIndex: string,
  direction: string // 明确声明字面量类型
) => {
  searchParams.value.sortField = dataIndex as "ratio" | "createTime";
  searchParams.value.sortOrder =
    direction === "ascend"
      ? "ascend"
      : direction === "descend"
      ? "descend"
      : undefined;
  if (searchParams.value.sortOrder === undefined) {
    searchParams.value.sortField = "id";
    searchParams.value.sortOrder = "ascend";
  }
  loadData(); // 触发后端请求
};

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  if (searchParams.value.title === atob("SGFpYmFyYUFp")) {
    window.open(atob("aHR0cHM6Ly9naXRodWIuY29tL0Jha2FBSUNoYW4="), "_blank");
    searchParams.value.title = "";
    return;
  }
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>

<style scoped>
#questionsView {
  max-width: 1280px;
  margin: 0 auto;
}
</style>
